package cn.edu.gzist.rabbit.rabbitmqclient;

import com.rabbitmq.client.*;

import java.io.UnsupportedEncodingException;

public class ConsumerTopic1 {
    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.exchangeDeclare(ProducerTopic.TOPIC_EXCHANGE, BuiltinExchangeType.TOPIC);
        channel.queueDeclare(ProducerTopic.TOPIC_QUEUE_1,true,false,false,null);
        //创建消费者，并设置消息处理
        Consumer consumer = new DefaultConsumer(channel){
            /**
             *
             * @param consumerTag：消息标签，在channel.basicConsume时候可以指定
             * @param envelope：消息包内容，可以从中取消息id，消息routingkey，交换机，消息和重转标记（收到消息失败后是否需要重新发送）
             * @param properties：消息属性
             * @param body：消息
             * @throws UnsupportedEncodingException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws UnsupportedEncodingException {
                System.out.println("路由key为："+envelope.getRoutingKey());
                System.out.println("交换机为："+envelope.getExchange());
                System.out.println("消息id为："+envelope.getDeliveryTag());
                //收到的消息
                System.out.println("接收到的消息为："+new String(body,"UTF-8"));
                System.out.println();
                System.out.println("=====================================================");
                System.out.println();
            }
        };

        /**
         * 监听消息
         * 参数一：队列名称
         * 参数二：是否自动确认。设置为true表示消息接收到自动向mq回复收到了，mq接收到回复后会删除消息，设置为false则需要手动确认
         */
        channel.basicConsume(ProducerTopic.TOPIC_QUEUE_1,true,consumer);


        //不关闭链接，应该一直坚挺消息

    }

}
